package com.erp.module.peibanPcode

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.erp.Interface.OnUserDataInterface
import com.erp.Myapp
import com.erp.R
import com.erp.bean.PmsDuihaoBean
import com.erp.myAdapter.ArrayAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.util.Dialogutil
import com.erp.util.JsonUtil
import com.erp.util.LanYaUtil
import com.erp.util.Myutil
import com.example.tsc.tscdll_test.TSCActivity
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.EtLanYa
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.LeftBt
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.RightBt
import kotlinx.android.synthetic.main.dialog_lanya_shezhi1.SpLanYa
import kotlinx.android.synthetic.main.fragment_peiban.AtDuihao
import kotlinx.android.synthetic.main.fragment_peiban.BtPiliangPcode
import kotlinx.android.synthetic.main.fragment_peiban.BtShengchengPcode
import kotlinx.android.synthetic.main.fragment_peiban.SpXuHao
import kotlinx.android.synthetic.main.fragment_peiban.ivShezhi
import kotlinx.android.synthetic.main.fragment_peiban.tvStartTime
import org.json.JSONException
import org.json.JSONObject

class FragmengtPeiban : BaseKFragment(), View.OnClickListener {

    private val f = "FragmentKPeiban"
    var model = PeibanModel()
    lateinit var duihaoCodes: MutableList<PmsDuihaoBean>
    lateinit var duihaoNames: MutableList<String>
    lateinit var updatedialog: AlertDialog
    var lanya  = "34:81:F4:CB:1D:11"
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_peiban
    }

    override fun initData() {
        duihaoCodes = ArrayList()
        duihaoNames = ArrayList()
        val listsp = ArrayList<String>()
        listsp.add("1")
        listsp.add("2")
        listsp.add("3")
        val sadapter = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listsp)
        SpXuHao.adapter = sadapter
        AtDuihao.setOnClickListener { AtDuihao.showDropDown() }
        BtShengchengPcode.setOnClickListener(this)
        BtPiliangPcode.setOnClickListener(this)
        ivShezhi.setOnClickListener(this)
        getDuihao()
        var ly = sp.getString("PMSlanya","")
        if(ly != null && ly != ""){
            lanya = ly;
        }
        tvStartTime.setOnClickListener(this)
//        tvEndTime.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v){
            BtShengchengPcode -> {
                postPcode()
            }
            ivShezhi -> {
                var c = context;
                if(c != null){
                    val dialog = AlertDialog.Builder(c).create()
                    dialog.setView(EditText(context))
                    dialog.show()
                    dialog.setContentView(R.layout.dialog_lanya_shezhi1)
                    val LanYaAdapter = ArrayAdapter(context, R.layout.lv_sp_tvitem, Myutil.ly_names())
                    dialog.SpLanYa.adapter = LanYaAdapter
                    dialog.SpLanYa.setSelection(LanYaUtil.ly_id(lanya))
                    val window = dialog.window
                    val p = window?.attributes // 获取对话框当前的参数值
                    p?.width = (sp.getInt("width", 0) * 0.9).toInt() // 宽度设置为屏幕的0.65
                    window?.attributes = p
                    dialog.LeftBt.setOnClickListener {
                        lanya = LanYaUtil.ly_address(dialog.SpLanYa.selectedItem.toString())
                        editor.putString("PMSlanya", lanya)
                        editor.commit()
                        Myutil.MyTost("打印机切换成功")
                    }
                    dialog.RightBt.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }
            BtPiliangPcode -> {
                postKeyPcode(0)
            }
            tvStartTime -> {
                Dialogutil.showBottoPopupWindowRiqi(tvStartTime, "选择结束时间", tvStartTime.text.toString(), activity)
                Myutil.notjianpan(context, ivShezhi)
            }
//            tvEndTime -> {
//                Dialogutil.showBottoPopupWindowRiqi(tvEndTime, "选择结束时间", tvEndTime.text.toString(), activity)
//                Myutil.notjianpan(context, ivShezhi)
//            }
        }
    }

    fun getDuihao() {
        model.getDuihao(context!!, object : OnUserDataInterface {
            override fun onUserData(data: String?) {
                Myutil.Mylog("getDuihao",data)
                DuihaoJson(data!!)
            }

            override fun onNot(throwable: String?) {
            }

        })
    }

    fun DuihaoJson(data : String){
        if (data==null){
            return
        }
        try {
            var ids: MutableList<String> = ArrayList()
            val jo = JSONObject(data)
            val js = JsonUtil.getjsvolue(jo,"data")
            for (i in 0 until js.length()) {

                val jodui = js.get(i) as JSONObject
                val bean = PmsDuihaoBean()
                val duihaoId =  JsonUtil.getvolue(jodui,"duihao_id")
                if(ids.contains(duihaoId)){
                    continue
                }
                bean.duihao_id = duihaoId
                bean.duihao_num = JsonUtil.getvolue(jodui,"duihao_num")
                bean.total = JsonUtil.getvolue(jodui,"total")
                bean.duihao_productive_at = JsonUtil.getvolue(jodui,"duihao_productive_at")
                bean.area_num = JsonUtil.getvolue(jodui,"area_num")
                bean.is_pcode = JsonUtil.getint(jodui,"is_pcode")
                ids.add(duihaoId)
                duihaoCodes.add(bean)
                duihaoCodes.count()
            }
            for (item in duihaoCodes) {
                duihaoNames.add("堆号:"+item.duihao_num+"  时间:"+item.duihao_productive_at.substring(0, 10))
            }

            val av = ArrayAdapter(context, R.layout.simple_at_item, duihaoNames)
            AtDuihao.setAdapter(av)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    /**
     * 打印对应下标的包条码
     * key:duihaoCodes的下标，当可以大于等于duihaoCodes的下标的长度时，中止打印
     * 当duihaoCodes.is_pcode等于1时，表示已经批量打印过，直接打印下一条
     * 打印成功并上传后自动开始吓一跳打印
     * 批量打印是序号设置为1
     */
    fun postKeyPcode(key : Int){
        if(tvStartTime.text.toString() == ""){
            Myutil.MyTost("请选择打印日期")
            return
        }
        if(key >= duihaoCodes.count()){
            return
        }
        if(duihaoCodes[key].is_pcode == 1){
            var k = key+1;
            postKeyPcode(k)
            return
        }

        val startTime = Integer.parseInt(Myutil.dateToStamp(tvStartTime.text.toString()))
        val endTime = startTime+86400
        val time = Integer.parseInt(Myutil.dateToStamp(duihaoCodes[key].duihao_productive_at))
        if(time < startTime || time  >= endTime){
            var k = key+1;
            postKeyPcode(k)
            return
        }
        var duihaoId  = ""
        var duihaoNum = ""
        val bianHao = "2000000"
        var total = ""
        var area_num = ""
        var duihao_productive_at = ""
        duihaoId = duihaoCodes[key].duihao_id
        duihaoNum = duihaoCodes[key].duihao_num
        total = duihaoCodes[key].total
        duihao_productive_at = duihaoCodes[key].duihao_productive_at
        area_num = duihaoCodes[key].area_num
        var xuhao = "1"
        var pcode = "DHID"+duihaoId+"-"+bianHao+"-"+total+"-"+duihaoNum+"dh"+"-"+xuhao
        val handle = @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message?) {
                msg.let {
                    updatedialog.dismiss()
                    updatedialog = Myutil.showupdatedialog(context, "正在上传包条码", false)
                    model.createPcode(context!!,pcode,total,duihaoId,object :OnUserDataInterface{
                        override fun onUserData(data: String?) {
                            updatedialog.dismiss()
                            try {
                                val jo = JSONObject(data)
                                if(!jo.getBoolean("ok")){
                                    val message = JsonUtil.getvolue(jo,"message");
//                                    Myutil.MyTost(JsonUtil.getvolue(jo,"message"))
                                    var c = context;
                                    if(c != null){
                                        val dialog = AlertDialog.Builder(c)
                                        dialog.setTitle("提示")
                                        dialog.setMessage(message)
                                        dialog.setPositiveButton("确定") { dialog, _ ->
                                            dialog.dismiss()
                                        }
                                        dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                                        dialog.show()
                                    }
                                }else{
                                    Myutil.MyTost("打印成功")
                                    duihaoCodes[key].is_pcode = 1
                                    var k = key+1;
                                    postKeyPcode(k)
                                }

                            } catch (e: JSONException) {
                                e.printStackTrace()
                            }
                        }

                        override fun onNot(throwable: String?) {
                            updatedialog.dismiss()
                        }

                    })
                }
            }
        }
        updatedialog = Myutil.showupdatedialog(context, "正在打印标签", false)
        val thread = object : Thread() {
            override fun run() {
                dayin(pcode,duihaoNum,total,area_num,duihao_productive_at.substring(0, 10),handle)
            }
        }
        thread.start()
    }

    fun postPcode() {
        var duihaoId  = ""
        var duihaoNum = ""
        val bianHao = "2000000"
        var total = ""
        var area_num = ""
        var duihao_productive_at = ""
        if(AtDuihao.text.toString() == ""){
            Myutil.MyTost("堆号必须选择")
        }
        var key = 0
        for (i in duihaoNames.indices) {
            if (duihaoNames[i] == AtDuihao.text.toString().trim { it <= ' ' }) {
                duihaoId = duihaoCodes[i].duihao_id
                duihaoNum = duihaoCodes[i].duihao_num
                total = duihaoCodes[i].total
                duihao_productive_at = duihaoCodes[i].duihao_productive_at
                area_num = duihaoCodes[i].area_num
                key = i
            }
        }
        var xuhao = SpXuHao.selectedItem.toString()

        var pcode = "DHID"+duihaoId+"-"+bianHao+"-"+total+"-"+duihaoNum+"dh"+"-"+xuhao
        val handle = @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message?) {
                msg.let {
                    updatedialog.dismiss()
                    updatedialog = Myutil.showupdatedialog(context, "正在上传包条码", false)
                    model.createPcode(context!!,pcode,total,duihaoId,object :OnUserDataInterface{
                        override fun onUserData(data: String?) {
                            updatedialog.dismiss()
                            try {
                                val jo = JSONObject(data)
                                if(!jo.getBoolean("ok")){
                                    Myutil.MyTost(JsonUtil.getvolue(jo,"message"))
                                }else{
                                    Myutil.MyTost("打印成功")
                                    duihaoCodes[key].is_pcode = 1
                                }

                            } catch (e: JSONException) {
                                e.printStackTrace()
                            }
                        }

                        override fun onNot(throwable: String?) {
                            updatedialog.dismiss()
                        }

                    })
                }
            }
        }
        updatedialog = Myutil.showupdatedialog(context, "正在打印标签", false)
        val thread = object : Thread() {
            override fun run() {
                dayin(pcode,duihaoNum,total,area_num,duihao_productive_at.substring(0, 10),handle)
            }
        }
        thread.start()
    }

    fun dayin(pcode:String,duihaoNum:String, totle : String,area_num:String,duihao_productive_at:String , handler: Handler){
        var tscActivity = TSCActivity()
        tscActivity.openport(lanya);
        tscActivity.setup(110, 40, 3, 4, 0, 2, 0);
        tscActivity.clearbuffer();
        tscActivity.sendcommand("\n");
        tscActivity.sendcommand("QRCODE 400,20,L,12,A,0,M2,S7,\"$pcode\"");
        tscActivity.sendcommand("\n");
        val typeface = Typeface.createFromAsset(Myapp.getContext().assets, "宋体-粗体.ttf")
        tscActivity.windowsfont(20, 20, 0, 40, typeface, "区号:  $area_num");
        tscActivity.windowsfont(20, 140, 0, 40, typeface, "提升机:  " );
        tscActivity.windowsfont(20, 260, 0, 40, typeface, "堆号:  $duihaoNum")
        tscActivity.windowsfont(20, 380, 0, 40, typeface, "包条码:")
        tscActivity.windowsfont(200, 380, 0, 40, typeface, pcode)
        tscActivity.windowsfont(800, 20, 0, 40, typeface, "规格:")
        tscActivity.windowsfont(800, 140, 0, 40, typeface, "数量:  $totle")
        tscActivity.windowsfont(800, 260, 0, 40, typeface, "日期:  $duihao_productive_at")
        Thread.sleep(500);
        tscActivity.printlabel(1, 1);
        tscActivity.closeport()
        val msg = Message.obtain()
        msg.obj = "信息"
        handler.sendMessage(msg)
    }
}
